#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/prctl.h>


using namespace std;

const int basesize = 1024;
const int argvnum = 64;
const int envnum = 64;
// 全局的命令行参数表
char *gargv[argvnum];
int gargc = 0;

// 全局的变量
int lastcode = 0;

// 我的系统的环境变量
char *genv[envnum];

// 全局的当前shell工作路径 
char pwd[basesize];
char pwdenv[basesize + 1024];

typedef enum
{
    RUNNING,
    STOPPED,
    DONE
} JobStatus;
//存储子进程信息
typedef struct 
{
    pid_t pid;
    char* cmd;
    JobStatus status;
    int jid;
} Job;
Job jobs[100];
int jobcnt = 1;

string GetUserName()
{
    string name = getenv("USER");
    return name.empty() ? "None" : name;
}

string GetHostName()
{
    char hostname[1024];
    int ret = gethostname(hostname,sizeof(hostname));
    if(ret == 0)
    {
        return hostname;
    }
    else{
        perror("gethostname() failed");
        return "None";
    }
}

string GetPwd()
{
    if(nullptr == getcwd(pwd, sizeof(pwd))) return "None";
    snprintf(pwdenv, sizeof(pwdenv),"PWD=%s", pwd);
    putenv(pwdenv); // PWD=XXX
    return pwd;

    //string pwd = getenv("PWD");
    //return pwd.empty() ? "None" : pwd;
}

string LastDir()
{
    string curr = GetPwd();
    if(curr == "/" || curr == "None") return curr;
    // /home/whb/XXX
    size_t pos = curr.rfind("/");
    if(pos == std::string::npos) return curr;
    return curr.substr(pos+1);
}

string MakeCommandLine()
{
    // [whb@bite-alicloud myshell]$ 
    char command_line[basesize];
    snprintf(command_line, basesize, "[%s@%s %s]# ",\
            GetUserName().c_str(), GetHostName().c_str(), LastDir().c_str());
    return command_line;
}

void PrintCommandLine() // 1. 命令行提示符
{
    printf("%s", MakeCommandLine().c_str());
    fflush(stdout);
}

bool GetCommandLine(char command_buffer[], int size)   // 2. 获取用户命令
{
    // 我们认为：我们要将用户输入的命令行，当做一个完整的字符串
    // "ls -a -l -n"
    char *result = fgets(command_buffer, size, stdin);
    if(!result)
    {
        return false;
    }
    command_buffer[strlen(command_buffer)-1] = 0;
    if(strlen(command_buffer) == 0) return false;
    return true;
}

void ParseCommandLine(char command_buffer[], int len) // 3. 分析命令
{
    (void)len;
    memset(gargv, 0, sizeof(gargv));
    gargc = 0;
    // "ls -a -l -n"
    const char *sep = " ";
    gargv[gargc++] = strtok(command_buffer, sep);
    // =是刻意写的
    while((bool)(gargv[gargc++] = strtok(nullptr, sep)));
    gargc--;
}

void debug()
{
    printf("argc: %d\n", gargc);
    for(int i = 0; gargv[i]; i++)
    {
        printf("argv[%d]: %s\n", i, gargv[i]);
    }
}

void handle_sig(int sig)
{
    pid_t pid;
    int status;
    while((pid = waitpid(-1,&status,WNOHANG)) > 0)
    {
        //printf("3");
        for(int i = 1;i < jobcnt;i++)
        {
            //printf("jobs[i].pid : %d , pid : %d",jobs[i].pid,pid);
            if(jobs[i].pid == pid)
            {
                // printf("1");
                if(WIFEXITED(status))
                {
                    jobs[i].status = DONE;
                }
                else 
                {
                    jobs[i].status = STOPPED;
                }
                break;
            }
        }
    }
}

// 在shell中
// 有些命令，必须由子进程来执行
// 有些命令，不能由子进程执行，要由shell自己执行 --- 内建命令 built command
bool ExecuteCommand()   // 4. 执行命令
{
    // 让子进程进行执行
    pid_t id = fork();
    if(id < 0) return false;
    if(id == 0)
    {
        //子进程
        // 1. 执行命令
        if(strcmp(gargv[gargc - 1],"&") == 0)
        {
            char* argv[argvnum];
            for(int i = 0;i < gargc - 1;i++)
            {
                argv[i] = gargv[i];
            }
            argv[gargc - 1] = NULL;
            setpgid(0,0);
            execvpe(gargv[0], argv, genv);
            _exit(1);
        }
        else
        execvpe(gargv[0], gargv, genv);
        // 2. 退出
        exit(1);
    }
    int status = 0;
    pid_t rid;
    if(strcmp(gargv[gargc - 1],"&") == 0)
    {
        printf("[%d] %d\n",jobcnt,id);
        jobs[jobcnt].pid = id;
        jobs[jobcnt].jid = jobcnt + 1;
        jobs[jobcnt].status = RUNNING;
        int len = strlen(gargv[0]);
        jobs[jobcnt].cmd = (char*)malloc(len + 1);
        strcpy(jobs[jobcnt].cmd,gargv[0]);
        for(int i = 1;i < gargc - 1;i++)
        {
            strcat(jobs[jobcnt].cmd," ");
            strcat(jobs[jobcnt].cmd,gargv[i]);
        }
        strcat(jobs[jobcnt].cmd," ");
        strcat(jobs[jobcnt].cmd,"&");
        jobcnt++;
        return true;
    }
    else
    rid = waitpid(id, &status, 0);
    if(rid > 0)
    {
        if(WIFEXITED(status))
        {
            lastcode = WEXITSTATUS(status);
        }
        else
        {
            lastcode = 100;
        }
        return true;
    }
    return false;
}

void AddEnv(const char *item)
{
    int index = 0;
    while(genv[index])
    {
        index++;
    }

    genv[index] = (char*)malloc(strlen(item)+1);
    strncpy(genv[index], item, strlen(item)+1);
    genv[++index] = nullptr;
}
void clean()//清理已经完成任务
{
    int j = 1;
    for(int i = 1;i < jobcnt;i++)
    {
        if(jobs[i].status != DONE)
        {
            jobs[j++] = jobs[i];
        }
        else
        free(jobs[i].cmd);
    }
    jobcnt = j;
}
// shell自己执行命令，本质是shell调用自己的函数
bool CheckAndExecBuiltCommand()
{
    if(strcmp(gargv[0], "jobs") == 0)
    {
        if(gargc == 1)
        {
            clean();
            for(int i = 1;i <= jobcnt - 1;i++)
            {
                printf("[%d] %s\n",jobs[i].pid,jobs[i].cmd);
            }
            lastcode = 0;
        }
        else
        {
            lastcode = 1;
        }
        return true;
    }
    else if(strcmp(gargv[0], "cd") == 0)
    {
        // 内建命令
        if(gargc == 2)
        {
            chdir(gargv[1]);
            lastcode = 0;
        }
        else
        {
            lastcode = 1;
        }
        return true;
    }
    else if(strcmp(gargv[0], "help") == 0)
    {
        if(gargc == 1)
        {
            printf("当前shell功能：\n");
            printf("1.实现cd env echo export等内键命令\n");
            printf("2.实现ls la -la 等外键命令\n");
            printf("3.实现了echo $?的错误码的返回\n");
            printf("3.实现了help,jobs功能\n");
            lastcode = 0;
        }
        else
        {
            lastcode = 1;
        }
        return true;
    }
    else if(strcmp(gargv[0], "export") == 0)
    {
        // export也是内建命令
        if(gargc == 2)
        {
            AddEnv(gargv[1]);
            lastcode = 0;
        }
        else
        {
            lastcode = 2;
        }
        return true;
    }
    else if(strcmp(gargv[0], "env") == 0)
    {
        for(int i = 0; genv[i]; i++)
        {
            printf("%s\n", genv[i]);
        }
        lastcode = 0;
        return true;
    }
    else if(strcmp(gargv[0], "echo") == 0)
    {
        if(gargc == 2)
        {
            // echo $?
            // echo $PATH
            // echo hello
            if(gargv[1][0] == '$')
            {
                if(gargv[1][1] == '?')
                {
                    printf("%d\n", lastcode);
                    lastcode = 0;
                }
            }
            else
            {
                printf("%s\n", gargv[1]);
                lastcode = 0;
            }
        }
        else
        {
            lastcode = 3;
        }
        return true;
    }
    return false;
}

// 作为一个shell，获取环境变量应该从系统的配置来
// 我们今天就直接从父shell中获取环境变量
void InitEnv()
{
    extern char **environ;
    int index = 0;
    while(environ[index])
    {
        genv[index] = (char*)malloc(strlen(environ[index])+1);
        strncpy(genv[index], environ[index], strlen(environ[index])+1);
        index++;
    }
    genv[index] = nullptr;
}
void Register()
{
    struct sigaction sa;
    sa.sa_handler = handle_sig;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;//如果系统调用被信号中断，内核会自动重启该调用,仅当子进程终止（而非暂停）时才会发送 SIGCHLD 信号
    sigaction(SIGCHLD, &sa, NULL);
}
int main()
{
    Register();
    InitEnv();
    char command_buffer[basesize];
    while(true)
    {
        PrintCommandLine(); // 1. 命令行提示符
        // command_buffer -> output
        if( !GetCommandLine(command_buffer, basesize) )   // 2. 获取用户命令
        {
            continue;
        }
        //printf("%s\n", command_buffer);
        //ls
        //"ls -a -b -c -d"->"ls" "-a" "-b" "-c" "-d"
        ParseCommandLine(command_buffer, strlen(command_buffer)); // 3. 分析命令
        if(strcmp(gargv[0], "bye") == 0 || strcmp(gargv[0], "exit") == 0 || strcmp(gargv[0], "quit") == 0)
        {
            return 0;
        }
        if ( CheckAndExecBuiltCommand() )
        {
            continue;
        }

        ExecuteCommand();   // 4. 执行命令
    }
    return 0;
}












